#include "Headers/UI/roomeditdialog.h"
#include "ui_roomeditdialog.h"

RoomEditDialog::RoomEditDialog(MyUtils::FormStatus formStatus, Room *room, QWidget *parent) :
    QDialog(parent),
    ui(new Ui::RoomEditDialog)
{
    ui->setupUi(this);

    this->setWindowFlags(Qt::Dialog |
                         Qt::WindowMinimizeButtonHint |
                         Qt::WindowMaximizeButtonHint);

    QTextCodec::setCodecForCStrings(QTextCodec::codecForName("UTF-8"));

    this->formStatus = formStatus;
    this->room = room;

    TypeOfRoomDataAccessor dataType;
    QSqlTableModel * model = dataType.getTypesOfRoom();
    ui->typeComboBox->setModel(model);
    ui->typeComboBox->setModelColumn(1);

    if (formStatus == MyUtils::Editing)
    {
        ui->numberLineEdit->setText(room->getNumber());
        ui->nameLineEdit->setText(room->getName());
        ui->floorSpinBox->setValue(room->getFloor());
        int type_id = room->getType().getId();//id типа комнаты
        for(int i = 0; i < model->rowCount(); i++)
        {
            if (model->data(model->index(i, 0)).toInt() == type_id)
                ui->typeComboBox->setCurrentIndex(i);
        }
    }
}

RoomEditDialog::~RoomEditDialog()
{
    delete ui;
}

/**
  Создать/Изменить
  */
void RoomEditDialog::on_createButton_clicked()
{
    RoomDataAccessor dataRoom;
    Room room;
    room.setNumber(ui->numberLineEdit->text());
    room.setName(ui->nameLineEdit->text());
    room.setFloor(ui->floorSpinBox->value());

    int currentIndex = ui->typeComboBox->currentIndex();
    int id_type = ui->typeComboBox->model()->data(ui->typeComboBox->model()->index(currentIndex, 0)).toInt();
    TypeOfRoomDataAccessor dataType;
    TypeOfRoom *typeOfRoom = dataType.getTypeOfRoom(id_type);

    room.setType(*typeOfRoom);

    if (formStatus == MyUtils::Adding)
    {
        dataRoom.setRoom(room);
    }
    else if (formStatus == MyUtils::Editing)
    {
        room.setId(this->room->getId());
        dataRoom.editRoom(room);
    }
    this->close();
}

/**
  Отмена
  */
void RoomEditDialog::on_cancelButton_clicked()
{
    this->close();
}

/**
  Типы комнат
  */
void RoomEditDialog::on_typePushButton_clicked()
{
    TypeOfRoomDialog typeDialog;
    typeDialog.exec();

    int currentIndex = ui->typeComboBox->currentIndex();
    int id_type = ui->typeComboBox->model()->data(ui->typeComboBox->model()->index(currentIndex, 0)).toInt();

    TypeOfRoomDataAccessor dataType;
    QSqlTableModel * model = dataType.getTypesOfRoom();
    ui->typeComboBox->setModel(model);
    ui->typeComboBox->setModelColumn(1);

    for(int i = 0; i < model->rowCount(); i++)
    {
        if (model->data(model->index(i, 0)).toInt() == id_type)
            ui->typeComboBox->setCurrentIndex(i);
    }
}
